package com.xyz.study.netty.cases.simple;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;

/**
 * TimeServerHandler
 *
 * @author xyz
 * @version 1.0.0
 * @since 2021/7/2
 */
public class TimeServerHandler extends ChannelInboundHandlerAdapter {

    private int counter;

    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
//        ByteBuf byteBuffer = (ByteBuf) o;
//        byte[] req = new byte[byteBuffer.readableBytes()];
//        byteBuffer.readBytes(req);
//        String body = new String(req, StandardCharsets.UTF_8);
        String body = (String) o;
        System.out.println("The simple server receive order : " + body + "; the counter is : " + ++counter);
        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
//        ByteBuf resp = Unpooled.copiedBuffer((currentTime + "\n").getBytes());
//        channelHandlerContext.writeAndFlush(resp);
        channelHandlerContext.writeAndFlush(currentTime + "\n");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}
